<template>
  <el-container>
    <el-header class="m-header">
      <!-- 搜索表单 -->
      <el-form style="padding-top: 5px"
               :model="where"
               label-width="77px"
               class="ele-form-search"
               @keyup.enter.native="reload"
               @submit.native.prevent>
        <el-row>
          <el-col :lg="4" :md="12">
            <el-form-item label="客户名称:">
              <el-input
                clearable
                v-model="where.custcode"
                placeholder="输入客户编码或客户名称查询"/>
            </el-form-item>
          </el-col>
          <el-col :lg="4" :md="12">
            <el-form-item label="药品编码:">
              <el-input
                clearable
                v-model="where.invcode"
                placeholder="输入药品编码或药品名称查询"/>
            </el-form-item>
          </el-col>
          <el-col :lg="4" :md="12">
            <el-form-item label="批号:">
              <el-input
                clearable
                v-model="where.vlotno"
                placeholder="输入批号"/>
            </el-form-item>
          </el-col>
          <!-- <el-col :lg="4" :md="12">
            <el-form-item label="状态:">
              <el-select
                clearable
                v-model="where.status"
                placeholder="请选择状态"
                class="ele-fluid">
                <el-option label="全部" value=""/>
                <el-option label="已退货" value="1"/>
                <el-option label="未退货" value="0"/>
              </el-select>
            </el-form-item>
          </el-col> -->
          <el-col :lg="4" :md="12">
            <div class="ele-form-actions">
              <el-checkbox v-model="showDetail" label="按客户展开" style="padding-right: 10px;padding-left: 10px" @change="showCustomer"></el-checkbox>
              <el-button
                type="primary"
                icon="el-icon-search"
                class="ele-btn-icon"
                size="small"
                @click="reload">查询
              </el-button>
              <el-button v-if="false"
                type="warning"
                icon="el-icon-save"
                class="ele-btn-icon"
                size="small"
                @click="checkInvoice">核销销售数量
              </el-button>
              <el-button @click="reset" size="small" class="ele-btn-icon">重置</el-button>
            </div>
          </el-col>
        </el-row>
      </el-form>
    </el-header>
    <el-main>
      <!-- 数据表格 -->
      <ele-pro-table
        ref="table"
        :where="where"
        :datasource="url"
        :columns="columnsMaterial"
        :need-page="true"
        :toolbar="false"
        :page-size="20"
        :selection.sync="selection"
        highlight-current-row
        @row-click="rowClick"
        @row-dblclick="showReturnForm"
        height="calc(100vh - 185px)">
        <!-- 表头工具栏 -->
        <template slot="toolbar" v-if="false">
          <el-button
            size="small"
            type="primary"
            icon="el-icon-plus"
            class="ele-btn-icon"
            @click="openEdit(null)"
            v-if="permission.includes('sys:c37infckscbillnew:add')">添加
          </el-button>
          <el-button
            size="small"
            type="danger"
            icon="el-icon-delete"
            class="ele-btn-icon"
            @click="removeBatch"
            v-if="permission.includes('sys:c37infckscbillnew:dall')">删除
          </el-button>
        </template>
        <!-- 操作列 -->
        <!-- 操作列 -->
        <template slot="action" slot-scope="{row}">
          <el-link
            type="primary"
            :underline="false"
            icon="el-icon-upload2"
            @click="openEdit(row)"
          >NC回写
          </el-link>
          <el-link
            type="success"
            slot="reference"
            :underline="false"
            icon="el-icon-document"
            @click="openLog(row)"
          >日志
          </el-link>
          <el-link v-if="false"
                   type="primary"
                   :underline="false"
                   icon="el-icon-search"
                   @click="openDetail(row)"
          >单据明细
          </el-link>

        </template>
      </ele-pro-table>
    </el-main>
    <!-- 编辑弹窗 -->
    <!-- <c37infckscbillnew-edit
      :data="current"
      :visible.sync="showEdit"
      @done="reload"/> -->
  </el-container>
</template>

<script>
import { mapGetters } from "vuex";

// import C37InfCkScBillNewEdit from './c37infckscbillnew-edit';

export default {
  name: 'ReturnOrder',
  // components: {C37InfCkScBillNewEdit},
  // components: {LogList,SaleForm},
  computed: {
    ...mapGetters(["permission"]),
  },
  data() {
    return {
      // 表格数据接口
      url: '/return/secondsalegroupstock',
      urlb: '/return/orderdetail',
      // 表格列配置
      columns: [
        // {
        //   columnKey: 'selection',
        //   type: 'selection',
        //   width: 45,
        //   align: 'center',
        //   fixed: "left"
        // },
        {
          columnKey: 'index',
          type: 'index',
          width: 45,
          align: 'center',
          // fixed: "left"
        },
        // {
        //   prop: 'dbilldate',
        //   label: '申请日期',
        //   showOverflowTooltip: true,
        //   minWidth: 80,
        //   align: 'center'
        // },
        // {
        //   prop: 'vbillcode',
        //   label: '申请单号',
        //   showOverflowTooltip: true,
        //   minWidth: 110,
        //   align: 'center'
        // },
        {
          prop: 'custcode',
          label: '客户编码',
          showOverflowTooltip: true,
          minWidth: 80,
          align: 'center'
        },
        {
          prop: 'custname',
          label: '客户名称',
          showOverflowTooltip: true,
          minWidth: 160,
          align: 'left'
        },
        {
          prop: 'invcode',
          label: '药品编码',
          showOverflowTooltip: true,
          minWidth: 80,
          align: 'center'
        },
        {
          prop: 'invname',
          label: '药品名称',
          showOverflowTooltip: true,
          minWidth: 140,
          align: 'left',
          // slot: 'realreason'
        },
        {
          prop: 'ssbk',
          label: '所属板块',
          showOverflowTooltip: true,
          minWidth: 180,
          align: 'left'
        },
        {
          prop: 'vlotno',
          label: '批号',
          showOverflowTooltip: true,
          minWidth: 130,
          align: 'left'
        },
        {
          prop: 'nnum',
          label: '申请数量',
          showOverflowTooltip: true,
          minWidth: 80,
          align: 'center'
        },
        {
          prop: 'soldnum',
          label: '已售数量',
          showOverflowTooltip: true,
          minWidth: 80,
          align: 'center'
        },
        {
          prop: 'remainnum',
          label: '可售数量',
          showOverflowTooltip: true,
          minWidth: 80,
          align: 'center'
        },
        {
          prop: 'nonhandnum',
          label: '库存数量',
          showOverflowTooltip: true,
          minWidth: 100,
          align: 'center'
        },

        // {
        //   columnKey: 'action',
        //   label: '操作',
        //   width: 160,
        //   align: 'center',
        //   resizable: false,
        //   slot: 'action',
        //   fixed: "right"
        // }
      ],
      columnsInv: [
        // {
        //   columnKey: 'selection',
        //   type: 'selection',
        //   width: 45,
        //   align: 'center',
        //   fixed: "left"
        // },
        {
          columnKey: 'index',
          type: 'index',
          width: 45,
          align: 'center',
          // fixed: "left"
        },
        {
          prop: 'invcode',
          label: '药品编码',
          showOverflowTooltip: true,
          minWidth: 80,
          align: 'center'
        },
        {
          prop: 'invname',
          label: '药品名称',
          showOverflowTooltip: true,
          minWidth: 140,
          align: 'left',
          // slot: 'realreason'
        },
        {
          prop: 'ssbk',
          label: '所属板块',
          showOverflowTooltip: true,
          minWidth: 180,
          align: 'left'
        },
        {
          prop: 'vlotno',
          label: '批号',
          showOverflowTooltip: true,
          minWidth: 130,
          align: 'left'
        },
        {
          prop: 'nnum',
          label: '申请数量',
          showOverflowTooltip: true,
          minWidth: 80,
          align: 'center'
        },
        {
          prop: 'soldnum',
          label: '已售数量',
          showOverflowTooltip: true,
          minWidth: 80,
          align: 'center'
        },
        {
          prop: 'remainnum',
          label: '可售数量',
          showOverflowTooltip: true,
          minWidth: 80,
          align: 'center'
        },
        {
          prop: 'nonhandnum',
          label: '库存数量',
          showOverflowTooltip: true,
          minWidth: 100,
          align: 'center'
        },

        // {
        //   columnKey: 'action',
        //   label: '操作',
        //   width: 160,
        //   align: 'center',
        //   resizable: false,
        //   slot: 'action',
        //   fixed: "right"
        // }
      ],
      columnsMaterial: [
        // {
        //   columnKey: 'selection',
        //   type: 'selection',
        //   width: 45,
        //   align: 'center',
        //   fixed: "left"
        // },
        {
          columnKey: 'index',
          type: 'index',
          width: 45,
          align: 'center',
          // fixed: "left"
        },
        {
          prop: 'invcode',
          label: '药品编码',
          showOverflowTooltip: true,
          minWidth: 80,
          align: 'center'
        },
        {
          prop: 'invname',
          label: '药品名称',
          showOverflowTooltip: true,
          minWidth: 140,
          align: 'left',
          // slot: 'realreason'
        },
        {
          prop: 'ssbk',
          label: '所属板块',
          showOverflowTooltip: true,
          minWidth: 180,
          align: 'left'
        },
        {
          prop: 'vlotno',
          label: '批号',
          showOverflowTooltip: true,
          minWidth: 130,
          align: 'left'
        },
        {
          prop: 'nnum',
          label: '入库数量',
          showOverflowTooltip: true,
          minWidth: 80,
          align: 'center'
        },
        {
          prop: 'soldnum',
          label: '已售数量',
          showOverflowTooltip: true,
          minWidth: 80,
          align: 'center'
        },
        {
          prop: 'remainnum',
          label: '可售数量',
          showOverflowTooltip: true,
          minWidth: 80,
          align: 'center'
        },
        {
          prop: 'nonhandnum',
          label: '库存数量',
          showOverflowTooltip: true,
          minWidth: 100,
          align: 'center'
        },
        {
          prop: 'nlocknum',
          label: '冻结数量',
          showOverflowTooltip: true,
          minWidth: 100,
          align: 'center'
        },

        // {
        //   columnKey: 'action',
        //   label: '操作',
        //   width: 160,
        //   align: 'center',
        //   resizable: false,
        //   slot: 'action',
        //   fixed: "right"
        // }
      ],

      // 表格搜索条件
      where: {riqiBegin:this.getFromDate(),riqiEnd:new Date()},
      // 表格选中数据
      selection: [],
      selectionMaterial:[],
      // 当前编辑数据
      current: null,
      // 是否显示编辑弹窗
      showEdit: false,
      showLog: false,
      showDetail:false,
      showReturn:false,
      activeName:'first',
      isFirst:true,
      isSecond:false,
      isThird:false,
      isFourth:false,
      //退货单明细
      orderDetail:[],
      //退货发票
      orderInvoice:[],
      orderReturnInvoice:[],
      soList:[],
      rkList:[],
      fpList:[]
    };
  },
  methods: {
    statusFormat(row, column,cellValue) {
      const daterc = row[column.property]
      if(daterc !=null){
        return cellValue=="N"?"已同步":"未同步";
      }
    },
    showCustomer(){

      this.url = this.showDetail?'/return/secondsalestock':'/return/secondsalegroupstock';
      this.columnsMaterial = this.showDetail?this.columns:this.columnsInv;
      this.$refs.table.doLayout();
      this.$refs.table.reload();
      this.$refs.table.doLayout();
    },
    updateMainReason(soldnum){
      this.selection[0].soldnum = soldnum;
      this.rowClick(this.selection[0]);
    },
    updateMaterialReason(reason,remark){
      this.selectionMaterial[0].realreason = reason;
      this.selectionMaterial[0].remark = remark;
      var param = {
        csaleorderid:this.selection[0].csaleorderid,
        csaleorderbid:this.selectionMaterial[0].csaleorderbid,
        realreason: reason,
        remark: this.selectionMaterial[0].remark
      };
      this.$http.post('/return/savereturn/',param).then(res => {
        if (res.data.code === 0) {
          this.$message.success(res.data.msg);
          //this.reload();
        } else {
          this.$message.error(res.data.msg);
        }
      }).catch(e => {
        this.$message.error(e.message);
      });



    },
    checkInvoice(){
      if(this.selection.length==0)
      {
        this.$message.info("请先选择退货申请单后进行核销操作");
        return;
      }
      if(this.selectionMaterial.length==0)
      {
        this.$message.info("请至少选择一行销售发票明细");
        return;
      }

      //可售数量
      var orderNum = Number(this.selection[0].remainnum)*-1;
      var totalNum = 0;
      var errinfo="";
      for(let v of this.selectionMaterial) {
        if (isNaN(v.realnum))
        {
          errinfo+=v.custname+"的本次销售数量无效";
          continue;
        }
        else
        {
          if(Number(v.realnum)>Number(v.remainnum))
          {
            errinfo+=v.custname+"的本次销售数量不能超过剩余数量";
            continue;
          }
          else {
            if(Number(v.realnum)==0)
            {
              errinfo+=v.custname+'的本次销售数量不能为0\n';
              continue;
            }
          }
        }
        totalNum+=Number(v.realnum);
      }
      if(errinfo!="")
      {
        //this.$message.error(errinfo);
        this.$message({
          dangerouslyUseHTMLString: true,
          message: errinfo,
          type: 'info'
        });
        return;
      }
      if(totalNum>orderNum)
      {
        this.$message.info("发票明细合计数量不能超过可售数量");
        return;
      }
      var params=[];
      for(let v of this.selectionMaterial) {
        var param = {
          csaleorderbid: this.selection[0].csaleorderbid,
          csaleinvoicebid: v.csaleinvoicebid,
          nnum: v.realnum
        };
        params.push(param);
      }
      var msg = "确定将【"+this.selection[0].dbilldate+"+"+this.selection[0].custname+"+";
      msg+= this.selection[0].vlotno+"+("+this.selection[0].nnum+")】的退货关联销售信息【";
      var index =0;
      for(let v of this.selectionMaterial) {
        msg+=v.vgoldtaxcode+"+"+v.custname+"+("+v.realnum+")";
        msg+=index==this.selectionMaterial.length-1?"】?":" / ";
        index+=1;
      }
      this.$confirm(msg, '提示', {
        type: 'warning'
      }).then(() => {
        this.$http.post('/return/saveresale/',params).then(res => {
          if (res.data.code === 0) {
            this.$message.success(res.data.msg);
            this.reload();
            this.rowClick(this.selection[0]);
          } else {
            this.$message.error(res.data.msg);
          }
        }).catch(e => {
          this.$message.error(e.message);
        });
      }).catch(() => {
      });

    },
    updateShowReturn(value)
    {
      this.showReturn = value;
    },
    showReturnForm(){
      this.showReturn = true;
    },
    handleClick(tab) {
      if (tab.name === 'first') {
        this.isFirst = true
        this.isSecond = false
        this.isThird = false
        this.isFourth = false
      }
      else if (tab.name === 'second') {
        this.isFirst = false
        this.isSecond = true
        this.isThird = false
        this.isFourth = false

      }
      else if (tab.name === 'third') {
        this.isFirst = false
        this.isSecond = false
        this.isThird = true
        this.isFourth = false

      }
      else if (tab.name === 'fourth') {
        this.isFirst = false
        this.isSecond = false
        this.isThird = false
        this.isFourth = true

      }
    },
    materialRowClick(row)
    {
      //this.selectionMaterial = [];
      //this.$refs.tableMaterial.clearSelection();
      //this.selectionMaterial.push(row);
      this.$refs.tableMaterial.toggleRowSelection(row,true);

    },
    async rowClick(row)
    {
      //console.log(row);
      this.selection = [];
      this.selectionMaterial = [];
      this.$refs.table.clearSelection();
      this.selection.push(row);
      this.$refs.table.toggleRowSelection(row,true);
      var res2 = await this.$http.get('/return/secondsaleinvoice?page=1&limit=1000&invcode='+row.invcode+'&vlotno='+row.vlotno+'&riqiBegin='+row.dbilldate);
      if(res2.status==200)
      {
        this.orderInvoice = res2.data.data.records;
      }

    },
    getFromDate() {
      const timeOne = new Date()
      const year = timeOne.getFullYear()
      let month = timeOne.getMonth()
      let day = 1
      //month = month < 10 ? '0' + month : month
      //day = day < 10 ? '0' + day : day
      ///const NOW_MONTHS_AGO = `${year}-${month}-${day}`
      return new Date(year,month,day);
    },
    /* 刷新表格 */
    reload() {
      this.$refs.table.reload({where: this.where});
    },
    /* 重置搜索 */
    reset() {
      this.where = {riqiBegin:this.getFromDate(),riqiEnd:new Date()};
      this.reload();
    },
    openLog(row){
      console.log(row);
      this.current = row;
      this.showLog = true;
    },
    openDetail(row){
      this.current = row;
      this.showDetail = true;
    },

    /* 显示编辑 */
    openEdit(row) {
      this.$confirm('确定要将选中的销售出库记录回写至NC吗?', '提示', {
        type: 'warning'
      }).then(() => {
        const loading = this.$loading({lock: true});
        this.$http.post('/shyp/zyyptck/', [row.csaleinvoicebid]).then(res => {
          loading.close();
          if (res.data.code === 0) {
            this.$message.success(res.data.msg);
            this.reload();
          } else {
            this.$message.error(res.data.msg);
          }
        }).catch(e => {
          loading.close();
          this.$message.error(e.message);
        });
      }).catch(() => {
      });
    },
    /* 删除 */
    remove(row) {
      const loading = this.$loading({lock: true});
      this.$http.delete('/c37infckscbillnew/delete', {id: row.id}).then(res => {
        loading.close();
        if (res.data.code === 0) {
          this.$message.success(res.data.msg);
          this.reload();
        } else {
          this.$message.error(res.data.msg);
        }
      }).catch(e => {
        loading.close();
        this.$message.error(e.message);
      });
    },
    /* 批量删除 */
    removeBatch() {
      if (!this.selection.length) {
        this.$message.error('请至少选择一条数据');
        return;
      }
      this.$confirm('确定要删除选中的销售出库/购进退出上传单表吗?', '提示', {
        type: 'warning'
      }).then(() => {
        const loading = this.$loading({lock: true});
        this.$http.delete('/c37infckscbillnew/delete', {id: this.selection.map(d => d.id)}).then(res => {
          loading.close();
          if (res.data.code === 0) {
            this.$message.success(res.data.msg);
            this.reload();
          } else {
            this.$message.error(res.data.msg);
          }
        }).catch(e => {
          loading.close();
          this.$message.error(e.message);
        });
      }).catch(() => {
      });
    },
  }
}
</script>

<style scoped>
.m-header {
  height: 45px !important;
}
.m-footer {
  height: 250px !important;
}
.el-row {
  margin-bottom: 5px;
  margin-top: 1px;
  display: flex;
  flex-wrap: wrap
}
/*对Tab标签页进行样式调整*/
.el-tabs__item.is-active {
  color: rgb(11, 150, 151);
}

.el-tabs__active-bar {
  background-color: rgb(11, 150, 151);
}

.el-tabs__item:hover {
  color: rgb(11, 150, 151);
}

.el-tabs {
  height: 100% !important;
  width: 100% !important;

}

.el-tabs__content {
  height: calc(100% - 55px);
  padding: 1px;
}
.el-tabs--border-card > .el-tabs__content {
  padding: 15px;
}

.el-tab-pane {
  height: 100%;
}

.el-tabs__header {
  padding: 0 30px;
}
.el-form-item{
  margin-bottom: 2px;
}
.ele-body {
  padding: 1px;
}
.el-dialog__body {
  padding-top: 2px;
  color: var(--color-text-regular);
  font-size: 14px;
  word-break: break-all;
}

.my-el-select /deep/ .el-input__inner::placeholder {
  color: #296dd3;
  text-align: left;
  font-size:10px;
  line-height: 30px;

}


</style>
